<!-- 绑定HIS -->
<template>
  <Dialogdrawerdefect :ddtvisible.sync="visible" size="495px" @close="handleCancel">
    <template slot="title">
      <div class="ddt-title">
        <span class="tit">绑定HIS--{{title}}</span>
        <el-button type="primary" @click="openDialogRoom" style="width: 120px" size="small">复制机房部位</el-button>
      </div>
    </template>
    <div class="checkroom-box" v-if="showCheckRoom" v-loading="checkroomLoading">
      <div class="checkroom-box-title">其他{{curRow.dep}}检查机房：</div>
      <div class="checkroom-box-cross">
        <el-tooltip
          class="item"
          effect="dark"
          content="关闭且还原成原来的本机房设置"
          placement="top"
        >
          <i
            @click="closeShowCheckRoom"
            style="font-size: 20px"
            class="el-icon-close close-icon"
          ></i>
        </el-tooltip>
      </div>
      <el-select filterable class="wd100" v-model="otherRegisterRoom" clearable size="small" placeholder="请选择" @change="selectChanged">
        <el-option
          v-for="(item, index) in registerRoomOptions"
          :key="index"
          :value="item"
          :label="item"
        ></el-option>
      </el-select>
    </div>
    <div class="cont_box" v-loading="loading" style="height:100%;padding-top: 0px !important;">
      <tree
        ref="tree"
        class="m-t-1 tree-dialog"
        :data="filterData"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :filter-node-method="filterNode"
        render-after-expand
        :auto-expand-parent="false"
        @current-change="checkChange"
        @check="checkChange"
      >
      </tree>
      <div class="buttons flex flex-row justify-between align-center">
        <div class="btn_checkall">
          <el-checkbox v-model="isSelectAll" :disabled="filterDataAll.length===0" @change="selectAll">全选</el-checkbox>
        </div>
        <div class="right-buttons">
          <el-button @click="handleCancel" size="small">关 闭</el-button>
          <el-button type="primary" @click="handleConfirm" size="small" :loading="loading" :disabled="loading">确 定</el-button>
        </div>
      </div>
    </div>
  </Dialogdrawerdefect>
</template>
<script>
// import { setLocalStorage, getLocalStorage } from '@/utils/localStorage' // removeLocalStorage
import { getHisTree, getHisRegisterList, checkroomBindHis, getcheckrooms } from '@/api/api.js'
import Dialogdrawerdefect from '@/components/dialogbox/dialogDrawerDefect'
import Tree from '@/assets/js/tree/index.js'
let initData = []
export default {
  name: '',
  mixins: [],
  components: { Dialogdrawerdefect, Tree },
  props: {
    showRight: {
      Boolean,
      default: false
    },
    curRow: {
      Object,
      default: () => {}
    },
    title: {
      String,
      default: ''
    }
  },
  data() {
    return {
      filterResult: [],
      showCheckRoom: false,
      filterIds: [],
      checkType: [],
      // 项目值域
      checkTypeSelectFilter: '',
      filterData: [],
      visible: false,
      loading: false,
      checkTypeData: [],
      checkTreeObj: {},
      hospitalCode: '',
      count: 100,
      detailData: [],
      clickNodes: [],
      filterDataAll: [],
      isSelectAll: false,
      defaultProps: {
        children: 'childrens',
        label: 'text'
      },
      bindCheckAll: false,
      checkRoomLimitPart: 0,
      depSet: this.$store.state.user.depSettings,
      depFilter: [],
      checkroomLoading: false,
      nodeLen: 0,
      isSelectData: [],
      otherRegisterRoom: '',
      registerRoomOptions: [], // 机房列表数组
      beginCheckItem: [], // 将开始的默认赋值存
      inputFilterValue: '', // 过滤的条件
      alreadyChecked: [],
      times: 0
    }
  },
  watch: {
    curRow: {
      handler(val) {
        if (val) {
          this.depFilter = JSON.parse(JSON.stringify(this.depSet.filter(item => item.dep === val.dep)))
          this.checkRoomLimitPart = this.depFilter.length > 0 ? this.depFilter[0].checkRoomLimitPart : this.checkRoomLimitPart
          this.count = 100
          this.isSelectAll = false
          this.$nextTick(() => { // 手动把滚动条置为最上面
            let node = document.getElementsByClassName('ddt-main')
            node[0].scrollTop = 0
            this.$refs.tree.refreshFilterValue()
          })
          this.checkTreeObj = {}
          this.getHisTree(val.hospitalCode, val.dep)
        //   this.getCheckData(val)
        }
      },
      deep: true
    },
    visible(val) {
      if (!val) {
        // this.curRow = ''
        this.$emit('changeCurRow', '')
        this.otherRegisterRoom = ''
        this.showCheckRoom = false
        this.registerRoomOptions = []
        this.checkroomLoading = false
      }
      this.$emit('update:showRight', val)
    },
    showRight(val) {
      this.visible = val
    },
    filterText(val) {
      this.filterTree('tree', this.checkType, val)
    },
    checkType(val) {
      this.filterIds = []
      this.filterTree('tree', val, this.filterText)
    }
    // checkTypeSelectFilter() {
    //   this.filterTree('tree', this.checkType, this.filterText)
    // }
  },
  computed: {},
  created() {

  },
  mounted() {
    this.init()
  },
  methods: {
    closeShowCheckRoom() {
      this.showCheckRoom = false
      this.getCheckData({
        hospitalCode: this.curRow.hospitalCode,
        checkRoom: this.curRow.checkRoom,
        dep: this.curRow.dep
      })
    },
    selectChanged(value) {
      this.getCheckData({
        hospitalCode: this.curRow.hospitalCode,
        checkRoom: value,
        dep: this.curRow.dep
      })
    },
    filterTree($el, val1, val2) {
      this.$refs[`${$el}`] && this.$refs[`${$el}`].filter(val1)
      this.$refs[`${$el}`] && this.$refs[`${$el}`].filter(val2)
      console.error('this.$refs[`${$el}`]', this.$refs[`${$el}`])
    },
    filterNodeMethod(nodeData) {
      console.log('filterNodeMethod=>nodeData', nodeData)
      if (nodeData !== '') {
        this.filterData = this.filterData.filter(node => {
          // 使用indexOf方法进行模糊匹配,筛选出满足一下条件的数据赋值给this.filterData
          if (node.childrens && node.childrens.length > 0) {
            node.expanded = true
            node.childrens = node.childrens.filter(item => {
              return item.id.indexOf(nodeData) !== -1
            })
            return node
          } else {
            return node.id.indexOf(nodeData) !== -1
          }
        })
        console.log('filterNodeMethod=>this.filterData--filter', this.filterData)
      } else if (nodeData === '') {
        this.filterData = initData // this.filterDataAll
      }
      console.log('filterNodeMethod=>this.filterData', this.filterData)
    },
    filterNode(value, data, node) {
      this.inputFilterValue = value
      let result = this.filterNodeComm('filterIds', 'checkTypeSelectFilter', value, data, node)
      return result
    },
    // 检查类型过滤，公用函数
    filterNodeComm(idsKey, stFilter, value, data, node) {
      if ((this[`${idsKey}`].length == 0 && !value) || (typeof value === 'object' && value.length === 0)) {
        node ? node.expanded = false : null
        return true
      }
      if (typeof value === 'string') {
        // console.log('this[`${stFilter}`]', this[`${stFilter}`])
        // debugger
        let flag = false
        // 判断文字查询是否指定字段
        if (this[`${stFilter}`] && this[`${stFilter}`] * 1 === 2) {
          if (data.level === 3) {
            if (this[`${idsKey}`].length === 0 || this[`${idsKey}`].length > 0 && this[`${idsKey}`].indexOf(data.grandId) > -1) {
              if (data.parentId.indexOf(value) !== -1) {
                return true
              } else {
                return false
              }
            } else {
              return false
            }
          }
        }
        if (this[`${stFilter}`] && this[`${stFilter}`] * 1 === 3 && data.level === 2) {
          return false
        }
        if (this[`${idsKey}`].length === 0 && (data && data.text.indexOf(value) !== -1)) {
          flag = true
        } else if (this[`${idsKey}`].length > 0 && (this[`${idsKey}`].indexOf(data.parentId) > -1 || this[`${idsKey}`].indexOf(data.grandId) > -1) && data.text.indexOf(value) !== -1) {
          flag = true
        }
        return flag
      } else if (typeof value === 'object') {
        let flag = false
        for (let v of value) {
          if (v === data.text || this[`${idsKey}`].indexOf(data.parentId) > -1 || this[`${idsKey}`].indexOf(data.grandId) > -1) {
            flag = true
            this[`${idsKey}`].push(data.id)
          }
        }
        console.log('this[`${idsKey}=>`]', this[`${idsKey}`])
        return flag
      }
    },
    init() {

    },
    getHisTree(hospitalCode, dep) {
      console.log('getHisTree')
      return new Promise(async resolve => {
        this.clickNodes = []
        if (this.checkTreeObj[hospitalCode + dep]) {
        //   this.checkTypeData = this.checkTreeObj[hospitalCode + dep]
          if (this.curRow) {
            this.getCheckData(this.curRow)
          }
          resolve()
          return
        }
        // this.checkTypeData = []
        this.loading = true
        await getHisTree({ HospitalCode: hospitalCode, dep }).then(res => {
          this.loading = false
          if (res && res.code === 10000) {
            this.checkTreeObj[hospitalCode + dep] = []
            let depNodes = res.content.childrens
            for (let i = 0; i < depNodes.length; i++) {
              let tempLevel1 = { text: depNodes[i].text, level: 1, childrens: [], id: depNodes[i].text }
              // 如果存在部位
              if (depNodes[i].childrens && depNodes[i].childrens.length !== 0 && !(this.checkRoomLimitPart)) {
                for (let j = 0; j < depNodes[i].childrens.length; j++) {
                  let level1Children = depNodes[i].childrens
                  // 加上level防止同名
                  let tempLevel2 = { text: level1Children[j].text, level: 2, childrens: [], id: tempLevel1.id + level1Children[j].text, parentId: tempLevel1.id }
                  //   if (level1Children[j].childrens && level1Children[j].childrens.length !== 0) {
                  //     tempLevel2.childrens = level1Children[j].childrens.map(item => {
                  //       return { text: item.text, level: 3, childrens: [], id: tempLevel2.id + item.text, parentId: tempLevel2.id, grandId: tempLevel2.parentId }
                  //     })
                  //   }
                  tempLevel1.childrens.push(tempLevel2)
                }
              }
              this.checkTreeObj[hospitalCode + dep].push(tempLevel1)
            }
            // this.checkTypeData = this.checkTreeObj[hospitalCode + dep]
          }
        }).catch(() => {
          this.loading = false
        })
        if (this.curRow) {
          this.getCheckData(this.curRow)
        }
        resolve()
      })
    },
    openDialogRoom() {
      this.checkroomLoading = true
      getcheckrooms({
        dep: this.curRow.dep,
        hospitalCode: this.curRow.hospitalCode
      }).then(res => {
        this.showCheckRoom = true
        this.checkroomLoading = false
        if (res && res.code === 10000) {
          this.registerRoomOptions = []
          res.content.list.forEach(item => {
            if (item.checkRoom !== this.title) {
              this.registerRoomOptions.push(item.checkRoom)
            }
          })
        }
      }).catch(() => {
        this.loading = false
      })
    },
    getCheckData(row) {
      console.warn(this.curRow)
      let data = {
        hospitalCode: row.hospitalCode,
        checkRoom: row.checkRoom
      }
      //   let filterTemp = this.checkTypeData.filter(item => item.id === row.dep)
      if (this.checkTreeObj[row.hospitalCode + row.dep]) {
        initData = this.checkTreeObj[row.hospitalCode + row.dep]
        // this.filterData = this.checkTreeObj[row.hospitalCode + row.dep].length > 100 ? this.checkTreeObj[row.hospitalCode + row.dep].slice(0, 100) : this.checkTreeObj[row.hospitalCode + row.dep]
        this.filterDataAll = this.checkTreeObj[row.hospitalCode + row.dep]
        this.filterData = this.checkTreeObj[row.hospitalCode + row.dep]
        console.log('getCheckData=>filterData', this.filterData)
        this.nodeLen = this.filterData.map(n => n.childrens).reduce((a, v) => a.concat(v), []).length
      } else {
        this.filterData = []
        this.filterDataAll = []
        this.nodeLen = 0
      }
      this.loading = true
      getHisRegisterList(data).then(res => {
        if (res && res.code === 10000) {
          this.detailData = res.content.list
          this.checkTreeRow(this.detailData)
          if (res.message) {
            this.$message.warning(res.message)
          }
        }
        this.loading = false
      })
    },
    // 进行默认勾选
    checkTreeRow(partList) {
      // this.$refs.tree.setCheckedKeys([])
      // this.$refs.tree.refreshFilterValue()
      this.$refs.tree.setCheckedNodes([])
      let checkTypeNodes = []
      if (partList.length != 0) {
        for (let i = 0; i < partList.length; i++) {
          // level2
          this.checkRoomLimitPart ? checkTypeNodes.push({ id: partList[i].bigpart }) : checkTypeNodes.push({ id: partList[i].bigpart + partList[i].smallpart })
        }
      }
      checkTypeNodes = checkTypeNodes.concat(this.clickNodes)
      this.beginCheckItem = JSON.parse(JSON.stringify(checkTypeNodes))
      checkTypeNodes.forEach(element => {
        this.alreadyChecked.push({ checked: true, id: element.id })
      })
      this.$refs.tree.setCheckedNodes(checkTypeNodes)
    },
    handleCancel() {
      this.$emit('update:showRight', false)
    },
    handleConfirm() {
      this.loading = true
      let checkedNodes = this.$refs.tree.getCheckedNodes()
      console.log('checkedNodes=====>', checkedNodes)
      console.log('this.isSelectData====>', this.isSelectData)
      let bigPart = checkedNodes.filter(item => item.level == 1)
      let smallPart = checkedNodes.filter(item => item.level == 2)
      let bindData = {
        hospitalCode: this.curRow.hospitalCode,
        checkRoom: this.curRow.checkRoom,
        hisParts: []
      }
      console.log('bigPart===>2', bigPart)
      console.log('smallPart===>', smallPart)
      let resultData = []
      for (let i = 0; i < smallPart.length; i++) {
        resultData.push({
          bigpart: smallPart[i].parentId,
          smallpart: smallPart[i].text
        })
      }
      if (this.checkRoomLimitPart) {
        for (let i = 0; i < bigPart.length; i++) {
          resultData.push({
            bigpart: bigPart[i].text,
            smallpart: bigPart[i].text
          })
        }
      }
      console.log('this.detailData=====>', this.detailData)
      // for (let i = 0; i < bigPart.length; i++) {
      //   console.log('bigPart====>', bigPart)
      //   for (let j = 0; j < bigPart[i].childrens.length; j++) {
      //     let id = bigPart[i].childrens[j].id
      //     let index = this.detailData.findIndex(v => {
      //       return v.bigpart + v.smallpart === id
      //     })
      //     console.log('index=====>', index)
      //     if (index === -1) {
      //       this.detailData.push({
      //         bigpart: bigPart[i].text,
      //         smallpart: bigPart[i].childrens[j].text
      //       })
      //     }
      //   }
      // }
      bindData.hisParts = resultData
      console.log('bindData.hisParts=====>', bindData.hisParts)
      console.log('bindData.hisParts=====>', JSON.stringify(bindData.hisParts))
      checkroomBindHis(bindData).then(res => {
        if (res && res.code === 10000) {
          this.bingShow = false
          this.loading = false
          this.handleCancel()
          this.$message.success('成功绑定')
        }
      })
    },
    load() {
      this.clickNodes = this.$refs.tree.getCheckedNodes()
      this.count += 100
      this.filterData = this.filterDataAll ? this.filterDataAll.slice(0, this.count) : []
      console.log('load---this.filterData', this.filterData)
      this.$nextTick(() => {
        this.checkTreeRow(this.detailData)
      })
    },
    checkChange(data, checked, indeterminate) {
      // 获得对应点击的第一级所包含的第二级的数量，来判断是否用我的方法进行勾选操作
      let filterDataSolve = JSON.parse(JSON.stringify(this.filterData)).filter(item => item.id === data.id)
      if (filterDataSolve.length > 0) {
        filterDataSolve = filterDataSolve[0].childrens.filter(item2 => item2.text.indexOf(this.inputFilterValue) != -1)
      }
      this.isSelectData = this.$refs.tree.getCheckedNodes(false, true)
      if (data.level === 1) {
        if (!checked) {
          data.childrens.forEach(el => {
            let index = this.detailData.findIndex(v => {
              return v.bigpart + v.smallpart === el.id
            })
            this.detailData.splice(index, 1)
          })
          this.isSelectAll = false
        } else {
          const checkedNodes = this.$refs.tree.getCheckedNodes().filter(node => node.parentId)
          let showContent = []
          let checks = 0
          // 如果输入的值不为空的话进入
          // 1.先判断该大部位的内容是不是全部显示，如果不是的话就走下面的逻辑
          // console.error(' || data.childrens.length === 0', filterDataSolve.length)
          if (data.childrens.length > filterDataSolve.length && filterDataSolve.length != 0) {
            // 如果当前的过滤不为空的话
            if (this.inputFilterValue != '') {
              // checkedNodes是该大部位勾选的全部内容
              checkedNodes.forEach(element => {
                // 对勾选的内容进行遍历处理
                // 2.如果勾选的全部内容包含过滤的内容，
                if (element.text.includes(this.inputFilterValue) && element.parentId === data.id) {
                  // 如果当前显示的项已经是勾选的状态，则需要将他们剔除，来实现取消勾选
                  // 如果默认勾选的内容里并没有包含该内容那就把加上
                  if (this.beginCheckItem.filter(item => item.id.includes(element.text)).length === 0) {
                    this.beginCheckItem.push({ id: element.parentId + element.text })
                    if (this.alreadyChecked.filter(item => item.id.includes(element.text)).length === 0) {
                      this.alreadyChecked.push({ checked: true, id: element.parentId + element.text })
                    }
                  } else {
                    checks = checks + 1
                    showContent.push({ id: element.parentId + element.text })
                    if (checks === filterDataSolve.length) {
                      showContent.forEach(element2 => {
                        this.beginCheckItem = this.beginCheckItem.filter(item => item.id != element2.id)
                        this.alreadyChecked = this.alreadyChecked.filter(item => item.id != element2.id)
                      })
                    }
                  }
                }
              })
            }
            this.$refs.tree.setCheckedNodes(this.beginCheckItem)
            // console.error('this.beginCheckItem', this.beginCheckItem)
          }
          this.isSelectAll = checkedNodes.length === this.nodeLen && this.nodeLen !== 0
        }
      }
    },
    // 全选
    // selectAll() {
    //   if (this.isSelectAll) {
    //     this.$refs.tree.setCheckedKeys([])
    //     this.inputFilterValue != '' ? null : this.detailData = []
    //     if (this.checkRoomLimitPart) {
    //       if (this.inputFilterValue != '') {
    //         this.filterDataAll.forEach(v => {
    //           v.text.indexOf(this.inputFilterValue) > -1 ? this.detailData.push(
    //             {
    //               bigpart: v.text
    //             }
    //           ) : null
    //         })
    //       } else {
    //         if (this.inputFilterValue != '') {
    //           this.filterDataAll.forEach(v => {
    //             v.text.indexOf(this.inputFilterValue) > -1 ? this.detailData.push(
    //               {
    //                 bigpart: v.text
    //               }
    //             ) : null
    //           })
    //         } else {
    //           this.filterDataAll.forEach(v => {
    //             this.detailData.push(
    //               {
    //                 bigpart: v.text
    //               }
    //             )
    //           })
    //         }
    //       }
    //     } else {
    //       if (this.inputFilterValue != '') {
    //         this.filterDataAll.forEach(v => {
    //           v.childrens.forEach(e => {
    //             e.text.indexOf(this.inputFilterValue) > -1 ? this.detailData.push(
    //               {
    //                 bigpart: v.text,
    //                 smallpart: e.text
    //               }
    //             ) : null
    //           })
    //         })
    //       } else {
    //         this.filterDataAll.forEach(v => {
    //           v.childrens.forEach(e => {
    //             this.detailData.push(
    //               {
    //                 bigpart: v.text,
    //                 smallpart: e.text
    //               }
    //             )
    //           })
    //         })
    //       }
    //     }
    //   } else {
    //     if (this.inputFilterValue != '') {
    //       this.checkRoomLimitPart ? this.detailData = this.detailData.filter(d => d.bigpart.indexOf(this.inputFilterValue) === -1) : this.detailData.filter(d => d.smallpart.indexOf(this.inputFilterValue) === -1)
    //     } else {
    //       this.detailData = []
    //       this.$refs.tree.setCheckedKeys([])
    //     }
    //   }
    //   this.checkTreeRow(this.detailData)
    //   // this.isSelectAll = !this.isSelectAll
    // }
    selectAll() {
      const { inputFilterValue, filterDataAll, isSelectAll, checkRoomLimitPart } = this
      const isFiltering = inputFilterValue !== ''
      if (isSelectAll) {
        this.$refs.tree.setCheckedKeys([])
        isFiltering ? null : this.detailData = []
        filterDataAll.forEach(v => {
          if (checkRoomLimitPart) {
            if (isFiltering) {
              if (v.text.includes(inputFilterValue)) {
                this.detailData.push({ bigpart: v.text })
              }
            } else {
              this.detailData.push({ bigpart: v.text })
            }
          } else {
            v.childrens.forEach(e => {
              if (isFiltering) {
                if (e.text.includes(inputFilterValue)) {
                  this.detailData.push({
                    bigpart: v.text,
                    smallpart: e.text
                  })
                }
              } else {
                this.detailData.push({
                  bigpart: v.text,
                  smallpart: e.text
                })
              }
            })
          }
        })
      } else {
        if (isFiltering) {
          if (this.detailData.filter(dd => dd.bigpart.includes(this.inputFilterValue)).length === this.filterDataAll.filter(fd => fd.id.includes(this.inputFilterValue))[0].childrens.length) {
            this.detailData = this.detailData.filter(dd => !(dd.bigpart.includes(this.inputFilterValue)))
          } else {
            this.detailData = checkRoomLimitPart ? this.detailData.filter(d => !(d.bigpart.includes(inputFilterValue))) : this.detailData.filter(d => !(d.smallpart.includes(inputFilterValue)))
          }
        } else {
          this.detailData = []
          this.$refs.tree.setCheckedKeys([])
        }
      }
      this.checkTreeRow(this.detailData)
    }
  },
  beforeDestroy() {},
  destroyed() {},
  beforeUpdate() {},
  updated() {}
}
</script>
<style lang='scss' scoped>
.tree-dialog{
    padding-bottom: 50px;
}
.buttons{
  width: 100%;
}
.ddt-title{
  display: flex;
  align-items: center;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  width: 100%;
  line-height: 18px;
  font-size: 16px;
  .tit{
    flex: 1;
  }
  .close{
    font-size: 18px;
    color: #666;
    cursor: pointer;
    &:hover{
      opacity: #333;
    }
  }
}
.checkroom-box {
  padding-left: 120px;padding-right:50px;margin: 0 0 20px;font-size: 15px;clear: both;
}
.checkroom-box-title {
  float: left;margin-left:-100px;line-height: 32px;
}
.checkroom-box-cross {
  margin-right: -17px;float: right;margin-top: 8px;
}
</style>
